const path = require('path');
const { StatusCodes } = require('http-status-codes');
const genRandomName = require('../utils/genRandomName');
const { BadRequestError, ServerError } = require('../errors');

const uploadsDir = [__dirname, '..', 'public', 'uploads'];
const imageMimeTypes = ['image/gif', 'image/png', 'image/jpeg'];

const createPromise = async (image) => {
   return new Promise((resolve, reject) => {
      if (!imageMimeTypes.includes(image.mimetype)) {
         reject(new BadRequestError(`上传${image.name}失败。仅支持${imageMimeTypes.map(item=>item.slice(6))}格式`));
      }

      const maxSize = 1024 * 1024 * 5;
      if (image.size > maxSize) {
         reject(
            new BadRequestError(`上传${image.name}失败。文件大小不能超过${maxSize / 1024 / 1024}M`)
         );
      }

      const imageName = genRandomName(image.name);
      let targetPath = path.resolve(...uploadsDir, imageName);

      image.mv(targetPath, (err) => {
         if (err) {
            console.log(err);
            reject(new ServerError(`上传${image.name}失败。服务器出现错误。`));
         }
         resolve(`/uploads/${imageName}`);
      });
   });
};

const uploadProductImage = async (req, res) => {
   if (!req.files || Object.keys(req.files).length === 0) {
      throw new BadRequestError('No files were uploaded.');
   }

   let promises = [];

   if (Array.isArray(req.files.image)) {
      req.files.image.forEach((image) => {
         promises.push(createPromise(image));
      });
   } else {
      promises.push(createPromise(req.files.image));
   }

   Promise.all(promises)
      .then((urls) => {
         res.status(StatusCodes.OK).json({
            msg: '上传成功',
            urls: urls,
         });
      })
      .catch((err) => {
         res.status(err.statusCode).json({
            msg: err.message,
         });
      });
};

module.exports = {
   uploadProductImage,
};
